﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vowei.Core.Models;
using System.Globalization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using Vowei.Core;

namespace Vowei.Data.Models
{
    [Serializable]
    public class DbResourceCalendar : ResourceCalendar
    {
        public DbResourceCalendar()
        {
        }

        public DbResourceCalendar(string name)
            : this(name, CultureInfo.CurrentUICulture)
        {
        }

        public DbResourceCalendar(string name, CultureInfo culture)
            : base(name, culture)
        {
        }

        protected DbResourceCalendar(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
        
        public void InitTypeFromStore()
        {
            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream(_calendarSettings, false))
            {
                var obj = (DbResourceCalendar)formatter.Deserialize(stream);
                Name = obj.Name;
                Culture = obj.Culture;
                WorkWeeks = obj.WorkWeeks;
                Exceptions = obj.Exceptions;
            }
        }

        private void PersistInstance()
        {
            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, this);
                _calendarSettings = stream.ToArray();
            }
        }

        private byte[] _calendarSettings;

        public byte[] CalendarSettings
        {
            get
            {
                if (_calendarSettings == null)
                    PersistInstance();

                return _calendarSettings;
            }
            set
            {
                if (value != _calendarSettings)
                {
                    _calendarSettings = value;
                    InitTypeFromStore();
                }
            }
        }
    }
}
